package Skill;

public class HIndex {
    public static void main(String[] args) {
        int[] citations = {3,0,6,1,5};
        System.out.println(hIndex(citations));
    }
    public static int hIndex(int[] citations) {
        QuickSort(citations);
        int left = 0;
        int right = citations.length;
        while (left<right){
            int mid = (right+left+1)/2;
            int count = 0;
            for (int citation:citations) {
                if (citation >= mid){
                    count++;
                }
            }
            if (count>=mid){
                left = mid;
            }else {
                right = mid-1;
            }
        }
        return left;
    }
    public static void QuickSort(int[] arr){
        if (arr == null || arr.length == 0){
            return;
        }
        QuickSort(arr,0,arr.length-1);
    }
    public static void QuickSort(int[] arr,int l,int r){
        if (l<r){
            swap(arr, l + (int) Math.random() * (r - l + 1), r);
            int[] p = partition(arr, l, r);
            QuickSort(arr, l, p[0] - 1);
            QuickSort(arr, p[1] + 1, r);
        }
    }
    public static int[] partition(int[] arr, int l, int r) {
        int less = l - 1;
        int more = r;
        while (l < more) {
            if (arr[l] < arr[r]) {
                swap(arr, ++less, l++);
            }
            if (arr[l] > arr[r]) {
                swap(arr, l, --more);
            }
            if (arr[l] == arr[r]) {
                l++;
            }
        }
        swap(arr, more, r);
        return new int[]{less + 1, more};
    }

    public static void swap(int[] arr, int l, int r) {
        int temp = arr[l];
        arr[l] = arr[r];
        arr[r] = temp;
    }
}
